package com.example.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Service
@Slf4j
public class TransactionService {

    public void sendQueue() {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            log.info("没有事务，异步发送消息到队列");
            return;
        }

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCompletion(int status) {
                if (status == TransactionSynchronization.STATUS_ROLLED_BACK) {
                    log.info("事务回滚，清理资源");
                }
                else {
                    log.info("事务执行完毕，发送消息到队列");
                }
            }
        });
    }

}
